﻿using System;
using System.ComponentModel;
using LukasKopenec.LocalizationSupport;
using Notoric.Gui.Windows;

namespace Notoric.Gui.Commands
{
    /// <summary>
    /// Implements a command that performs the undo operation.
    /// </summary>
    public class UndoCommand : RibbonCommand
    {
        #region Constructors

        /// <summary>
        /// Creates a new <see cref="UndoCommand"/> instance.
        /// </summary>
        /// <param name="mainWindow">The main application window</param>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="mainWindow"/> is <see langword="null"/>.
        /// </exception>
        public UndoCommand(MainWindow mainWindow)
            : base(mainWindow)
        {
            mainWindow.StackManager.PropertyChanged += new PropertyChangedEventHandler(StackManager_PropertyChanged);
            ScreenTipTitle = (string)LocalizationManager.GetValue("Ribbon.CommandTitles.Edit.Undo");
            ScreenTipText = (string)LocalizationManager.GetValue("Ribbon.CommandToolTips.Undo.Text");
        }

        #endregion

        #region ICommand Members

        /// <inheritdoc/>
        public override bool CanExecute(object parameter)
        {
            if (!ApplicationWindow.StackManager.CanUndo)
            {
                if (ApplicationWindow.StackManager.ActiveUndoCommand == null)
                    DisableReason = (string)LocalizationManager.GetValue("Ribbon.CommandToolTips.Undo.DisableReason.Empty");
                else
                    DisableReason = (string)LocalizationManager.GetValue("Ribbon.CommandToolTips.Undo.DisableReason.Integrity");
            }
            return ApplicationWindow.StackManager.CanUndo;
        }

        /// <inheritdoc/>
        public override void Execute(object parameter)
        {
            ApplicationWindow.StackManager.ActiveUndoCommand.Execute(null);
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Occurs when a property of the application window's stack manager has changed.
        /// </summary>
        /// <param name="sender">Object that has sent the event</param>
        /// <param name="e">Event data</param>
        private void StackManager_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "CanUndo")
                RaiseCanExecuteChanged();
            if (e.PropertyName == "ActiveUndoCommand")
            {
                if (ApplicationWindow.StackManager.ActiveUndoCommand != null)
                    ScreenTipTitle = string.Format((string)LocalizationManager.GetValue("Ribbon.CommandToolTips.Undo"), ApplicationWindow.StackManager.ActiveUndoCommand.Name);
                else
                    ScreenTipTitle = (string)LocalizationManager.GetValue("Ribbon.CommandTitles.Edit.Undo");
            }
        }

        #endregion
    }
}
